import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'

const websocket = class {
  url = [process.env.VUE_APP_BASE_API] + '/ws/base-data/gs-notify'
  stompClient = null;
  connected = false;

  constructor(url) {
    if (url) {
      this.url = url
    }
    this.stompClient = Stomp.over(new SockJS(this.url))
  }

  send(msg) {
    console.log('Send message:test', msg)
    if (this.stompClient && this.stompClient.connected) {
      msg = { name: 'test send msg 回话' }
      this.stompClient.send('/app/hello', JSON.stringify(msg), {})
    }
  }

  subscribe(endpoint, callback) {
    this.connect().then(res => {
      // console.log("开始订阅,connect-info:", res)
      this.stompClient.subscribe(endpoint, data => {
        // console.log("订阅[" + endpoint + "]收到消息:", data);
        callback(JSON.parse(data.body))
      })
    })
  }

  connect() {
    return new Promise(resolve => {
      if (!this.connected) {
        this.stompClient.connect({}, frame => {
          this.connected = true
          resolve(frame)
        },
        error => {
          console.log('失败连接websocket error:', error)
          this.connected = false
          this.missConnect()
          resolve(error)
        }
        )
      } else {
        resolve('已经连接成功')
      }
    })
  }

  missConnect() {
    // TODO 应该提示到界面上
    console.log('失去连接,请稍后刷新界面重试')
  }
}

export default websocket
